package android.longs.study.upgrade.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONSerializer;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import android.longs.study.base.ResponeModel;
import android.longs.study.upgrade.dao.UpgradeDao;
import android.longs.study.upgrade.dao.UpgradeDaoImp;
import android.longs.study.upgrade.model.UpgradeModel;

public class UpgradeServiceImple implements UpgradeService {
    private UpgradeDao dao = new  UpgradeDaoImp();

    @Override
    public String queryLastVersion() {
	UpgradeModel queryLast = dao.queryLast();
	ResponeModel<UpgradeModel> responeModel = new ResponeModel<UpgradeModel>();
	if (queryLast!=null) {
	    responeModel.code="1000";
	    responeModel.message = "请求成功";
	    responeModel.content = queryLast;
	} else {
	    responeModel.code="1002";
	    responeModel.message = "无数据 ";
	}

	String string = JSONSerializer.toJSON(responeModel).toString();
	return string;
    }

    /**
     * 添加新的版本 
     */
    @Override
    public String addUpgradeModel(HttpServletRequest request,ServletContext servletContext) {


	//dao.addUpgradeModel(upgradeModel);

	addFunction(request,servletContext);
	return null;
    }

    private void addFunction(HttpServletRequest request,ServletContext servletContext) {
	//判断用户的请求内容是不是multipart/form-data
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if(!isMultipart){
	    throw new RuntimeException("Your form is not multipart/form-data");
	}


	//创建DiskFileItemFactory对象
	DiskFileItemFactory factory = new DiskFileItemFactory();
	//factory.setRepository(new File("d:/"));//更改临时文件的存放目录
	//创建核心解析类ServletFileUpload
	ServletFileUpload sfu = new ServletFileUpload(factory);
	//	sfu.setFileSizeMax(3*1024*1024);//单位是字节：单个文件
	//	sfu.setSizeMax(6*1024*1024);//总文件大小
	//解析请求对象：List<FileItem>
	List<FileItem> items = new ArrayList<FileItem>(0);
	try {
	    items = sfu.parseRequest(request);
	}catch (FileUploadBase.FileSizeLimitExceededException e) {
	    System.out.println("单文件不能超过3M");
	    e.printStackTrace();
	}catch(FileUploadBase.SizeLimitExceededException e){
	    System.out.println("总文件不能超过6M");
	    e.printStackTrace();
	}catch (FileUploadException e) {
	    e.printStackTrace();
	}
	//遍历List：处理普通字段和上传字段
	for(FileItem item:items){
	    if(item.isFormField()){
		//普通字段
		processFormField(item);
	    }else{
		//上传字段
		processUploadField(item,servletContext);
	    }
	}




    }

    private void processUploadField(FileItem item,ServletContext servletContext) {
	try {
	    InputStream in = item.getInputStream();//上传文件的输入流
	    String filename = item.getName();
	    //在服务器上找一个存文件的地方：/files目录
	    String storeDirecotryRealPath = servletContext.getRealPath("/WEB-INF/app/verson");
	    File storeDirectory = new File(storeDirecotryRealPath);//File即代表文件也代表目录
	    if(!storeDirectory.exists()){
		storeDirectory.mkdirs();//目录不存在就创建
	    }
	    //截取上传的文件名
	    if(filename!=null){
		filename = FilenameUtils.getName(filename);
	    }

	    File file = new File(storeDirectory,filename);
	    String path = file.getPath();
	    //自动清除临时文件
	    item.write(file);

	    //构建输出流：IO操作
	    OutputStream out = new FileOutputStream(new File(storeDirectory,filename));

	    int len = -1;
	    byte buf[] = new byte[1024*1024];
	    while((len=in.read(buf))!=-1){
		out.write(buf, 0, len);
	    }
	    in.close();
	    out.close();
	    item.delete();
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    private void processFormField(FileItem item) {
	String fieldName = item.getFieldName();//字段名
	String fieldValue = null;
	try {
	    fieldValue = item.getString("UTF-8");
	} catch (UnsupportedEncodingException e) {
	    e.printStackTrace();
	}//字段值
	System.out.println(fieldName+"="+fieldValue);

    }

    @Override
    public String addUpgradeModel(HttpServletRequest request) {
	
	
	String versonName = request.getParameter("versonName");
	
	String versonCode = request.getParameter("versonCode");
	
	String versonDes = request.getParameter("versonDes");
	
	String path = request.getParameter("path");
	


	UpgradeModel upgradeModel = new UpgradeModel();
	upgradeModel.appPath=path;
	upgradeModel.isForce=0;
	upgradeModel.version=versonName;
	upgradeModel.versionCode=versonCode;
	upgradeModel.versionDescribe=versonDes;
	
	String result = "添加成功  .. .. .. "+upgradeModel.version;
	try {
	    dao.addUpgradeModel(upgradeModel);
	} catch (Exception e) {
	    result="添加异常 "+e.getMessage();
	}
	
	return result;
    }

}
